package com.baidu.controller;

import com.baidu.common.R;
import com.baidu.pojo.User;
import com.baidu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.baidu.common.Constant.LOGIN_USER;

@Controller
public class LoginController {
    @Autowired
    UserService ser;

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping(value = {"/","login"})
    public String login(){
        return "login";
    }

    /**
     * 登录方法
     * @return
     */
    @RequestMapping("loginSign")
    @ResponseBody
    public R loginSign(String username, String password, HttpServletRequest request){
        if(StringUtils.isEmpty(username)){
            return R.error("请输入用户名");
        }
        if(StringUtils.isEmpty(password)){
            return R.error("请输入密码");
        }

        User u  = ser.selectByUsernameAndPassword(username,password);
        if(u!=null){
            //  判断是否为空
            // 去user表  查询
            // 是否有 查询出的 user
            // 登录成功   将 user放入session中
            HttpSession session = request.getSession();
            session.setAttribute(LOGIN_USER,u);
            return R.ok();
        }else {
            return R.error("未查询到该用户");
        }
    }

    @RequestMapping("index")
    public String index(){
        return "index";
    }
    @RequestMapping("main")
    public String main(){
        return "main";
    }
}
